import 'dart:async';
import 'dart:io';

import 'package:path/path.dart';
// import 'package:path_provider/path_provider.dart';
import 'ClientModel.dart';
import 'package:sqflite_common/sqlite_api.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:path/path.dart' as p;
class DBProvider {
  DBProvider._();

  static final DBProvider db = DBProvider._();

  Database? _database;

  Future<Database> get database async {
    // Directory support = await getApplicationSupportDirectory();
    // print(support);
    print("get database");
    if (_database != null) return _database as Database;
    // if _database is null we instantiate it
    print("before initDB");
    _database = await initDB();
    Database db=_database as Database;
    //await db.execute("CREATE TABLE todos_todo (id        INTEGER       NOT NULL  PRIMARY KEY AUTOINCREMENT,    text      VARCHAR (100) NOT NULL,    completed BOOL          NOT NULL);");
    return db;
  }

  initDB() async {
    print("initDB");
    sqfliteFfiInit();
    print('Current path style: ${p.style}');

    print('Current process path: ${p.current}'); 
    // Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = p.join(p.current, "data.sqlite");
    print(path);
    var databaseFactory = databaseFactoryFfi;
    return await databaseFactory.openDatabase(path);
    //return await databaseFactory.openDatabase(":memory:");
  }

  newClient(Client newClient) async {
    final db = await database;
    print(newClient);
    print("here");
    print(newClient.completed);
    print(newClient.text);
    print(clientToJson(newClient));
    //get the biggest id in the table
    //var table = await db.rawQuery("SELECT MAX(id)+1 as id FROM todos_todo");
    //int id = table.first["id"];
    //print(id);
    //insert to the table using the new id
    var raw = await db.rawInsert(
        "INSERT Into todos_todo (text,completed)"
        " VALUES (?,?)",
        [newClient.text, newClient.completed?1:0]);
    print(raw);
    return raw;
  }

  blockOrUnblock(Client client) async {
    final db = await database;
    Client blocked = Client(
        client.id,
        client.text,
        !client.completed);
    var res = await db.update("todos_todo", blocked.toMap(),
        where: "id = ?", whereArgs: [client.id]);
    return res;
  }

  updateClient(Client newClient) async {
    final db = await database;
    var res = await db.update("todos_todo", newClient.toMap(),
        where: "id = ?", whereArgs: [newClient.id]);
    return res;
  }

  getClient(int id) async {
    final db = await database;
    var res = await db.query("todos_todo", where: "id = ?", whereArgs: [id]);
    return res.isNotEmpty ? Client.fromMap(res.first) : null;
  }

  Future<List<Client>> getBlockedClients() async {
    final db = await database;

    print("works");
    // var res = await db.rawQuery("SELECT * FROM Client WHERE blocked=1");
    var res = await db.query("todos_todo", where: "completed = ? ", whereArgs: [1]);

    List<Client> list =
        res.isNotEmpty ? res.map((c) => Client.fromMap(c)).toList() : [];
    return list;
  }

  Future<List<Client>> getAllClients() async {
    final db = await database;
    var res = await db.query("todos_todo");
    print("res");
    print(res);
    List<Client> list =
        res.isNotEmpty ? res.map((c) => Client.fromMap(c)).toList() : [];
    print("list===");
    print(list);
    return list;
  }

  deleteClient(int id) async {
    final db = await database;
    return db.delete("todos_todo", where: "id = ?", whereArgs: [id]);
  }

  deleteAll() async {
    final db = await database;
    db.rawDelete("Delete * from todos_todo");
  }
}
//([id] integer PRIMARY KEY NOT NULL, [bh] varchar (30), [name] varchar (30) NOT NULL, [guige] varchar (30), [ct] integer NOT NULL, [danwei] varchar (30) NOT NULL, [image] VARCHAR (100), [name_en] CHAR (30), [beizhu] CHAR (30))